package top.yrlby.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author BaiYang
 * @time 2022/9/6
 */

@Slf4j
@Component //将如下的类产生对象，放入IoC容器
public class MyMetaObjectHandler  implements MetaObjectHandler {


    /**
     * 插入操作，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.getOriginalObject().toString());
//        metaObject.setValue("createTime", LocalDateTime.now());
//        metaObject.setValue("updateTime",LocalDateTime.now());
//
//        //在此类中无法获取到request, session对象，因此无法获取到当前登录用户ID
//        metaObject.setValue("createUser",BaseContext.getCurrentId());
//        metaObject.setValue("updateUser",BaseContext.getCurrentId());

        this.fillStrategy(metaObject, "createTime", LocalDateTime.now());
        this.fillStrategy(metaObject, "updateTime", LocalDateTime.now());
        this.fillStrategy(metaObject, "createUser", BaseContext.getCurrentId());
        this.fillStrategy(metaObject, "updateUser", BaseContext.getCurrentId());
    }

    /**
     * 更新操作，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.getOriginalObject().toString());

//        metaObject.setValue("updateTime",LocalDateTime.now());
//        metaObject.setValue("updateUser",BaseContext.getCurrentId());

        this.fillStrategy(metaObject, "updateTime", LocalDateTime.now());
        this.fillStrategy(metaObject, "updateUser", BaseContext.getCurrentId());

    }
}
